#include <codex/os/CDX_Timer.h>
namespace codex
{
namespace system
{
	NativeTimerInteger timer::m_freq;
	NativeTimerInteger timer::m_current;
	NativeTimerInteger timer::m_last;

	tBOOL timer::m_active = FALSE;
	tBOOL timer::m_timerStopped = TRUE;
	tBOOL timer::m_limitFPS = FALSE;
	tBOOL timer::m_doFrame = TRUE;

	tDOUBLE timer::m_elapsed = 0.0;

	tDOUBLE timer::m_timePerFrame = 1.0 / 60.0;
	tDOUBLE timer::m_fpsElapsed = 0.0;

	void timer::init()
	{
		m_freq.QuadPart = 0;
		m_current.QuadPart = 0;
		m_last.QuadPart = 0;
		m_active = FALSE;
		m_timerStopped = TRUE;
		m_limitFPS = FALSE;
		m_doFrame = TRUE;
		m_elapsed = 0.0;
	
		m_active = QueryPerformanceFrequency(&m_freq) != 0;

		cdxAssert( m_active && "High Frequency clock not available" );
	}

	void timer::setFPS( tU32 fps )
	{
		if( fps == 0 )
			m_limitFPS = FALSE;
		else
		{
			m_limitFPS = TRUE;
			m_timePerFrame = 1.0 / tDOUBLE(fps);
		}
	}

	void timer::start()
	{
		if( m_timerStopped )
		{
			QueryPerformanceCounter( &m_last );
			m_elapsed	= 0.0;
			m_timerStopped = FALSE;
		}
	}

	void timer::stop()
	{
		if( !m_timerStopped )
		{
			m_timerStopped = TRUE;
			m_elapsed	= 0.0;
		}
	}
	
	void timer::update()
	{
		QueryPerformanceCounter( &m_current );
		m_elapsed = (m_current.QuadPart - m_last.QuadPart) / (tDOUBLE)m_freq.QuadPart;
		m_last = m_current;

		if( m_limitFPS )
		{
			m_fpsElapsed += m_elapsed;
			if( m_fpsElapsed >= m_timePerFrame )
			{
				m_elapsed = m_fpsElapsed;
				m_fpsElapsed -= m_timePerFrame;
				m_doFrame = TRUE;
			}else
				m_doFrame = FALSE;
		}
	}

	tFLOAT timer::getElapsedTime()
	{
		return (tFLOAT)m_elapsed;
	}

	tU64 timer::getCurrentTime()
	{
		return m_current.QuadPart;
	}

	tBOOL timer::fps()
	{
		return m_doFrame;
	}
	
}
}